package com.xbongbong.parent.parse.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DefaultTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkKeyFieldInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.UserHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.formdata.pojo.dto.LinkDataDTO;
import com.xbongbong.pro.formexplain.pojo.DefaultLinkInfoPojo;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2021/06/07 17:24
 */
@Component
public class LinkDataHelp {

    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private BaseFormDataLinkDataHelp baseFormDataLinkDataHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private CommonHelp commonHelp;

    public Map<String, PaasFormDataEntityExt> getLinkDataOfBusinessType(LinkResultDataDTO linkResultDataDTO, LinkResultDataVO linkResultDataVO) throws XbbException {
        // key为：saas是“业务类型_表单数据id” paas是“表单数据id”
        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Object> linkDataSet = linkResultDataVO.getLinkDataSet();
        if (linkDataSet.isEmpty()) {
            return formDataMap;
        }
        // 获取所有的关联数据的表单
        List<FieldAttrEntity> explainList = linkResultDataVO.getExplainList();
        // 检索除子表单中的关联数据
        List<LinkInfoPojo> linkInfoList = ProFormHelp.getLinkInfoNoSubForm(explainList);
        Map<Integer, LinkInfoPojo> saasLinkInfoMap = new HashMap<>(linkInfoList.size());
        List<LinkInfoPojo> paasLinkInfoList = new ArrayList<>();
        List<Long> formIdList = new ArrayList<>();
        for (LinkInfoPojo linkInfoPojo : linkInfoList) {
            formIdList.add(linkInfoPojo.getLinkFormId());
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), linkInfoPojo.getLinkSaasMark())) {
                saasLinkInfoMap.put(linkInfoPojo.getLinkBusinessType(), linkInfoPojo);
            } else {
                paasLinkInfoList.add(linkInfoPojo);
            }
        }
        List<Long> ids = new ArrayList<>();
        linkDataSet.forEach((item)->{
            ids.add(Long.valueOf(String.valueOf(item)));
        });
        String corpid = linkResultDataDTO.getCorpid();
        Iterator<Integer> saasIterator = saasLinkInfoMap.keySet().iterator();

        while (saasIterator.hasNext()) {
            LinkInfoPojo linkInfoPojo = saasLinkInfoMap.get(saasIterator.next());
            // 获取检索字段
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkInfoPojo.getLinkBusinessType(), linkInfoPojo.getLinkSaasMark());

            List<PaasFormDataEntityExt> dataList = paasEsModel.getByIdList(ids, corpid, linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType(), new ArrayList<>(), indexTypeEnum);
            if (Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())){
                formDataHelp.setChildSpecification(dataList,corpid);
            }
            List<Long> idIn = new ArrayList<>();
            dataList.forEach(item->{
                String key = linkInfoPojo.getLinkBusinessType() + "_" + item.getDataId();
                formDataMap.put(key, item) ;
                idIn.add(item.getDataId());
            });
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Boolean search = linkResultDataDTO.getSearchUserTeam();
            if (Objects.isNull(search) || search) {
                formDataFormExplainHelper.getUserIdMap(idIn, corpid, linkInfoPojo.getLinkBusinessType(), false, mainUserMap, coUserMap);
            }
            linkResultDataVO.setMainUserMap(mainUserMap);
            linkResultDataVO.setCoUserMap(coUserMap);
        }
        if (CollectionsUtil.isNotEmpty(paasLinkInfoList)) {

            // 获取检索字段

            List<PaasFormDataEntityExt> dataList = paasEsModel.getByIdList(ids, corpid, SaasMarkEnum.PAAS.getCode(), 0, new ArrayList<>(), IndexTypeEnum.IDX_FORM_DATA);
            dataList.forEach(item -> {
                String key = item.getDataId().toString();
                formDataMap.put(key, item);
            });
        }
        return formDataMap;
    }

    /**
     * 根据关联数据字段，去查询对应的数据
     * @param linkResultDataDTO
     * @param linkResultDataVO
     * @return
     * @throws XbbException
     */
    public Map<String, PaasFormDataEntityExt> getLinkData4Field(LinkResultDataDTO linkResultDataDTO, LinkResultDataVO linkResultDataVO) throws XbbException {
        // key为：saas是“业务类型_表单数据id” paas是“表单数据id”
        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Object> linkDataSet = linkResultDataVO.getLinkDataSet();
        if (linkDataSet.isEmpty()) {
            return formDataMap;
        }
        // linkDataMap格式：{"text_1": [23,25,36], "subForm_1": [{"text_1": [23,25,36]}, {"text_2": [23,25,36]}]}
        Map<String, Object> linkDataMap = linkResultDataVO.getLinkData();

        // {"text_1": [123], "subForm_1.text_1": [123, 456]}
        Map<String, Set<Long>> linkDataValueMap = setLinkDataValue(linkDataMap);
        // 获取所有的关联数据的表单
        List<FieldAttrEntity> explainList = linkResultDataVO.getExplainList();
        // key:attr value:LinkInfoPojo
        Map<String, LinkInfoPojo> linkInfoList = getLinkInfoIncludeProductMap(explainList);
        Map<Integer, LinkInfoPojo> saasLinkInfoMap = new HashMap<>(linkInfoList.size());
        // 数据字段
        Map<Integer, Set<Long>> saasLinkInfoValueMap = new HashMap<>(linkInfoList.size());
        List<LinkInfoPojo> paasLinkInfoList = new ArrayList<>();
        Set<Long> paasLinkInfoValueMap = new HashSet<>();
        List<Long> formIdList = new ArrayList<>();
        Iterator<String> iterator = linkInfoList.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (!linkDataValueMap.containsKey(key)) {
                continue;
            }
            LinkInfoPojo linkInfoPojo = linkInfoList.get(key);
            formIdList.add(linkInfoPojo.getLinkFormId());
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), linkInfoPojo.getLinkSaasMark())) {
                saasLinkInfoMap.put(linkInfoPojo.getLinkBusinessType(), linkInfoPojo);
                if (saasLinkInfoValueMap.containsKey(linkInfoPojo.getLinkBusinessType())) {
                    Set<Long> idSet = saasLinkInfoValueMap.get(linkInfoPojo.getLinkBusinessType());
                    idSet.addAll(linkDataValueMap.get(key));
                    saasLinkInfoValueMap.put(linkInfoPojo.getLinkBusinessType(), idSet);
                } else {
                    saasLinkInfoValueMap.put(linkInfoPojo.getLinkBusinessType(), linkDataValueMap.get(key));
                }
            } else {
                paasLinkInfoList.add(linkInfoPojo);
                paasLinkInfoValueMap.addAll(linkDataValueMap.get(key));
            }
        }
        Set<Long> ids;
        String corpid = linkResultDataDTO.getCorpid();
        Iterator<Integer> saasIterator = saasLinkInfoMap.keySet().iterator();

        while (saasIterator.hasNext()) {
            Integer businessType = saasIterator.next();
            LinkInfoPojo linkInfoPojo = saasLinkInfoMap.get(businessType);
            ids = saasLinkInfoValueMap.get(businessType);
            if (CollectionUtils.isEmpty(ids)) {
                continue;
            }
            // 获取检索字段
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkInfoPojo.getLinkBusinessType(), linkInfoPojo.getLinkSaasMark());
            List<PaasFormDataEntityExt> dataList = paasEsModel.getByIdList(ids, corpid, linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType(), new ArrayList<>(), indexTypeEnum);
            if (Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())){
                formDataHelp.setChildSpecification(dataList,corpid);
            }
            if (Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.SERVICE_PROJECT.getCode())){
                formDataHelp.setServiceUnit(dataList,corpid);
            }
            List<Long> idIn = new ArrayList<>();
            dataList.forEach(item->{
                String key = linkInfoPojo.getLinkBusinessType() + "_" + item.getDataId();
                idIn.add(item.getDataId());
                formDataMap.put(key, item) ;
            });
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Boolean search = linkResultDataDTO.getSearchUserTeam();
            if (Objects.isNull(search) || search) {
                formDataFormExplainHelper.getUserIdMap(idIn, corpid, linkInfoPojo.getLinkBusinessType(), false, mainUserMap, coUserMap);
            }
            linkResultDataVO.setMainUserMap(mainUserMap);
            linkResultDataVO.setCoUserMap(coUserMap);
        }
        if (CollectionsUtil.isNotEmpty(paasLinkInfoList)) {

            // 获取检索字段
            List<PaasFormDataEntityExt> dataList = paasEsModel.getByIdList(paasLinkInfoValueMap, corpid, SaasMarkEnum.PAAS.getCode(), 0, new ArrayList<>(), IndexTypeEnum.IDX_FORM_DATA);
            dataList.forEach(item -> {
                String key = item.getDataId().toString();
                formDataMap.put(key, item);
            });
        }
        return formDataMap;
    }

    /**
     * 设置主键字段-详情和编辑
     * @param fieldAttrEntity
     */
    public void setLinkKey(FieldAttrEntity fieldAttrEntity) {
        if (Objects.nonNull(fieldAttrEntity.getLinkInfo())) {
            LinkKeyFieldInfoPojo linkKeyAttr = fieldAttrEntity.getLinkInfo().getLinkKeyAttr();
            // 设置主键字段
            if (Objects.nonNull(linkKeyAttr)) {
                List<LinkedAttrPoJo> linkedAttr = fieldAttrEntity.getLinkInfo().getLinkedAttr();

                Map<String, LinkedAttrPoJo> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                linkedAttr.forEach(item->{
                    explainMap.put(item.getAttr(), item);
                });
                if (!explainMap.containsKey(linkKeyAttr.getAttr())) {
                    LinkedAttrPoJo linkedAttrPoJo = new LinkedAttrPoJo();
                    BeanUtil.copyProperties(linkKeyAttr, linkedAttrPoJo);
                    linkedAttr.add(linkedAttrPoJo);
                }
            }
        }
    }

    /**
     * 去掉主键字段-详情和编辑
     * @param fieldAttrEntity
     */
    public void removeLinkKey(FieldAttrEntity fieldAttrEntity) {
        if (Objects.nonNull(fieldAttrEntity.getLinkInfo())) {
            LinkKeyFieldInfoPojo linkKeyAttr = fieldAttrEntity.getLinkInfo().getLinkKeyAttr();
            // 去掉主键字段
            if (Objects.nonNull(linkKeyAttr)) {
                List<LinkedAttrPoJo> linkedAttr = fieldAttrEntity.getLinkInfo().getLinkedAttr();
                Map<String, LinkedAttrPoJo> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                linkedAttr.forEach(item->{
                    explainMap.put(item.getAttr(), item);
                });
                if (!explainMap.containsKey(linkKeyAttr.getAttr())) {
                    Iterator<LinkedAttrPoJo> iterator = linkedAttr.iterator();
                    while (iterator.hasNext()) {
                        if (Objects.equals(iterator.next().getAttr(), linkKeyAttr.getAttr())) {
                            iterator.remove();
                        }
                    }
                }
            }
        }
    }

    /**
     * 设置默认的关联数据
     * @param explainList
     * @param formDataAddGetDTO
     * @param handlerExplainVO
     * @return void
     * @author 吴峰
     * @date 2021/3/10 9:31
     * @throws XbbException
     */
    public void setDefaultLinkData(List<FieldAttrEntity> explainList, FormDataAddGetDTO formDataAddGetDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        if (Objects.isNull(formDataAddGetDTO.getDefaultLinkInfo())) {
            return;
        }
        DefaultLinkInfoPojo defaultLinkInfo = formDataAddGetDTO.getDefaultLinkInfo();
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), defaultLinkInfo.getBusinessType())) {
            // 新建产品不设置默认的关联数据，因为有父子产品的问题存在，让用户自己选择
            return;
        }
        String attr = defaultLinkInfo.getLinkList().getAttr();
        // 本表单的
        FieldAttrEntity fieldAttrEntity = getLinkInfo(explainList, attr);
        if (Objects.isNull(fieldAttrEntity) || Objects.isNull(fieldAttrEntity.getLinkInfo())) {
            return;
        }
        LinkInfoPojo linkInfoPojo = fieldAttrEntity.getLinkInfo();
        if (CollectionsUtil.isNotEmpty(linkInfoPojo.getCondition())) {
            if (Objects.nonNull(formDataAddGetDTO.getCustomDefault()) && formDataAddGetDTO.getCustomDefault()) {
                // 表单新建获取自定义默认值的时候，有过滤条件也显示默认值
            } else {
                // 关联列表新建时会将当前的关联数据作为默认值带出来，如果有条件的话不显示默认值
                // fieldAttrEntity.setDefaultAttr(new DefaultAttrPoJo());
                // bugID=37425 如果有条件的话，需要手动选择关联数据
                return;
            }
        }
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataAddGetDTO.getCorpid(), defaultLinkInfo.getBusinessType(), defaultLinkInfo.getSaasMark());
        // 查询本表单的数据
        // PaasFormDataEntityExt item = paasEsModel.getByKey(defaultLinkInfo.getDataId(), formDataAddGetDTO.getCorpid(), indexTypeEnum, null);
        List<Long> dataIdList = new ArrayList<>();
        Object dataId = defaultLinkInfo.getDataId();
        if (dataId instanceof Number) {
            dataIdList.add(Long.parseLong(dataId.toString()));
        } else if (dataId instanceof List) {
            dataIdList = JSON.parseArray(JSON.toJSONString(dataId), Long.class);
        } else {
            return;
        }
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = paasEsModel.getByIdList(dataIdList, formDataAddGetDTO.getCorpid(), defaultLinkInfo.getSaasMark(), defaultLinkInfo.getBusinessType(), null, indexTypeEnum);
        if (CollectionsUtil.isEmpty(paasFormDataEntityExtList)) {
            // fix-bug：32543 加个判断避免下面空指针错误
            return;
        }
        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasFormDataEntityExtList.forEach(item -> {
            String value = item.getDataId().toString();
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), defaultLinkInfo.getSaasMark())) {
                value = defaultLinkInfo.getBusinessType() + "_" + value;
            }
            formDataMap.put(value, item);
        });

        Map<String, PaasFormExplainEntity> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, WorkOrderExplainEntity> workOrderFormExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkInfoPojo.getLinkBusinessType())) {
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(linkInfoPojo.getLinkFormId(), formDataAddGetDTO.getCorpid());
            workOrderFormExplainMap.put(linkInfoPojo.getLinkFormId().toString(), workOrderExplainEntity);
        } else {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(linkInfoPojo.getLinkFormId(), formDataAddGetDTO.getCorpid());
            formExplainMap.put(linkInfoPojo.getLinkFormId().toString(), paasFormExplainEntity);
        }

        Map<String, UserEntity> userMap = handlerExplainVO.getUserMap();
        Map<String, DepartmentEntity> departmentMap = handlerExplainVO.getDepartmentMap();
        if (userMap.isEmpty()) {
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataAddGetDTO,userAndDepartmentGetDTO);
            // userMap = userHelp.getUserMap(userAndDepartmentGetDTO);
            userMap = commonHelp.getUserMap(userAndDepartmentGetDTO,BasicConstant.ONE);
        }
        if (departmentMap.isEmpty()) {
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataAddGetDTO,userAndDepartmentGetDTO);
            // departmentMap = userHelp.getDepartmentMap(userAndDepartmentGetDTO);
            departmentMap = commonHelp.getDepartmentMap(userAndDepartmentGetDTO);
        }
        // 设置主键字段
        setLinkKey(fieldAttrEntity);
        LinkDataDTO linkDataDTO = new LinkDataDTO();
        BeanUtil.copyProperties(formDataAddGetDTO, linkDataDTO);
        linkDataDTO.setSaasMark(linkInfoPojo.getLinkSaasMark());
        linkDataDTO.setBusinessType(linkInfoPojo.getLinkBusinessType());

        JSONArray linkDataResult = new JSONArray();
        for (Long linkDataId : dataIdList) {
            JSONObject jsonObject = baseFormDataLinkDataHelp.getLinkData(fieldAttrEntity, formDataMap, linkDataId.toString(), formExplainMap, workOrderFormExplainMap, userMap, departmentMap, linkDataDTO, fieldAttrEntity.getLinkInfo().getLinkedAttr());
            if(jsonObject == null){
                // sonObject = new JSONObject();
                continue;
            }
            JSONObject linkDataJsonObject = new JSONObject();
            linkDataJsonObject.put("dataId", linkDataId);
            linkDataJsonObject.put("id", linkDataId);
            linkDataJsonObject.put("data", jsonObject);
            linkDataResult.add(linkDataJsonObject);
        }
        if (CollectionsUtil.isNotEmpty(linkDataResult)) {
            setDefaultLinkData(formDataAddGetDTO.getCustomDefault(), explainList, attr, linkDataResult);
        }
    }

    /**
     * 设置关联数据的默认值
     * @param explainList
     * @param attr
     * @param data
     */
    private void setDefaultLinkData(Boolean customDefault, List<FieldAttrEntity> explainList, String attr, JSONArray data) {
        for (FieldAttrEntity item : explainList) {
            // 在关联列表开启时，快速新建数据的时候，默认值设置当前表单的数据
            if ((Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), item.getFieldType())) && Objects.equals(item.getAttr(), attr)) {
                DefaultAttrPoJo defaultAttrPoJo = item.getDefaultAttr();
                if (Objects.isNull(defaultAttrPoJo)) {
                    defaultAttrPoJo = new DefaultAttrPoJo();
                }
                if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType())) {
                    defaultAttrPoJo.setDefaultType(DefaultTypeEnum.LINK_DATA.getAlias());
                    defaultAttrPoJo.setDefaultValue(data.getJSONObject(0));
                } else {
                    defaultAttrPoJo.setDefaultType(DefaultTypeEnum.LINK_DATA_MULTI.getAlias());
                    defaultAttrPoJo.setDefaultValue(data);
                }
                if (Objects.nonNull(customDefault) && customDefault) {
                    defaultAttrPoJo.setDefaultType(DefaultTypeEnum.CUSTOM.getAlias());
                }
                item.setDefaultAttr(defaultAttrPoJo);
            } else if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                List<? extends FieldAttrEntity> subExplainList = item.getSubForm().getItems();
                for (FieldAttrEntity subItem : subExplainList) {
                    if ((Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subItem.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), subItem.getFieldType())) && Objects.equals(item.getAttr()+ "." + subItem.getAttr(), attr)) {
                        DefaultAttrPoJo defaultAttrPoJo = subItem.getDefaultAttr();
                        if (Objects.isNull(defaultAttrPoJo)) {
                            defaultAttrPoJo = new DefaultAttrPoJo();
                        }
                        if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subItem.getFieldType())) {
                            defaultAttrPoJo.setDefaultType(DefaultTypeEnum.LINK_DATA.getAlias());
                            defaultAttrPoJo.setDefaultValue(data.getJSONObject(0));
                        } else {
                            defaultAttrPoJo.setDefaultType(DefaultTypeEnum.LINK_DATA_MULTI.getAlias());
                            defaultAttrPoJo.setDefaultValue(data);
                        }
                        if (Objects.nonNull(customDefault) && customDefault) {
                            defaultAttrPoJo.setDefaultType(DefaultTypeEnum.CUSTOM.getAlias());
                        }
                        subItem.setDefaultAttr(defaultAttrPoJo);
                    }
                }
                item.getSubForm().setItems(subExplainList);
            }
        }
    }

    /**
     * 设置关联数据
     * @param explainList
     * @param attr
     * @return
     */
    private FieldAttrEntity getLinkInfo(List<FieldAttrEntity> explainList, String attr) {
        for (FieldAttrEntity item : explainList) {
            if ((Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), item.getFieldType())) && Objects.equals(item.getAttr(), attr)) {
                return item;
            } else if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(item.getSubForm().getItems()), FieldAttrEntity.class);
                for (FieldAttrEntity subItem : subExplainList) {
                    if ((Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subItem.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), subItem.getFieldType())) && Objects.equals(item.getAttr()+ "." + subItem.getAttr(), attr)) {
                        return subItem;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取每个字段下的关联数据
     * @param linkDataMap
     * 详情页格式：{"text_1": 23, "subForm_1": [{"text_1": 23}]}
     * 列表页的数据经过FormDataListAnalysisDataHelp.getLinkDataSet(paasFormDataEntityExt.getData(), subFormLinkDataMap, linkDataSet, linkDataIdSet, linkAttrSet, linkDataIdMap)
     * 处理后的格式：{"text_1": [23,25,36], "subForm_1": [{"text_1": [23,25,36]}, {"text_2": [23,25,36]}]}
     * @return  返回格式： {"text_1": [123], "subForm_1.text_1": [123, 456]}
     */
    // TODO 这里肯定会有问题的啊 by HU
    private static Map<String, Set<Long>> setLinkDataValue(Map<String, Object> linkDataMap) {
        Map<String, Set<Long>> linkDataValueMap = new HashMap<>(linkDataMap.size());
        linkDataMap.forEach((key, item)->{
            if (item instanceof List) {
                JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(item));
                for (int i = 0; i < jsonArray.size(); i++) {
                    if (jsonArray.get(i) instanceof Map) {
                        // 子表单关联数据处理
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        jsonObject.forEach((attr, value) -> {
                            String subKey = key + "." + attr;
                            setLinkDataValue(linkDataValueMap, subKey, value);
                        });
                    } else if (jsonArray.get(i) instanceof Number) {
                        // 关联多选处理
                        setLinkDataValue(linkDataValueMap, key, jsonArray.get(i));
                    }
                }
            } else {
                setLinkDataValue(linkDataValueMap, key, item);
            }
        });
        return linkDataValueMap;
    }

    private static void setLinkDataValue(Map<String, Set<Long>> linkDataValueMap, String key, Object item) {
        if (linkDataValueMap.containsKey(key)) {
            Set<Long> idSet = linkDataValueMap.get(key);
            if (item instanceof Collection) {
                List<Long> id = JSON.parseArray(JSON.toJSONString(item), Long.class);
                idSet.addAll(id);
                linkDataValueMap.put(key, idSet);
            } else {
                Long id = Long.valueOf(String.valueOf(item));
                idSet.add(id);
                linkDataValueMap.put(key, idSet);
            }
        } else {
            Set<Long> idSet = new HashSet<>();
            if (item instanceof Collection) {
                List<Long> id = JSON.parseArray(JSON.toJSONString(item), Long.class);
                idSet.addAll(id);
                linkDataValueMap.put(key, idSet);
            } else {
                Long id = Long.valueOf(String.valueOf(item));
                idSet.add(id);
                linkDataValueMap.put(key, idSet);
            }

        }
    }



    /**
     * 获取所有关联数据的字段，准备搜索各个业务的数据
     * @param explainList
     * @return
     */
    private static Map<String, LinkInfoPojo> getLinkInfoIncludeProductMap(List<FieldAttrEntity> explainList) {
        Map<String, LinkInfoPojo> linkInfoMap = new HashMap<>(explainList.size());
        explainList.forEach(item->{
            if (ExplainUtil.isSubForm(item.getFieldType())) {
                List<? extends FieldAttrEntity> subExplainList = item.getSubForm().getItems();
                subExplainList.forEach(subItem->{
                    if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subItem.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), subItem.getFieldType())){
                        linkInfoMap.put(item.getAttr()+ StringConstant.POINT+subItem.getAttr(), subItem.getLinkInfo());
                    }
                });
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), item.getFieldType())) {
                linkInfoMap.put(item.getAttr(), item.getLinkInfo());
            }
        });
        return linkInfoMap;
    }
}
